// components/selectCols/selectCols.js
/**
 * 221102 yan 修改 1、初始点击弹出标识时才加载获取数据，增加初始数据isLoad是否加载标识  2、增加 filterTable属性，有传入该属性时，搜索的table_id以及筛选SearchWhere中table_id用该值。
 */
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 弹出弹层标识
    flag: {
      type: Boolean,
      value: false,
      async observer(newVal, oldVal) {
        let {table, showFields,isLoad} = this.data;
        if (!isLoad && table){
          await this.getTableCols(table,showFields);
          this.getDataPage();
          this.data.isLoad = true;
        }
        this.setData({
          show: true,
        });
      },
    },
    // 模块名称
    table: {
      type: String,
      value: '',
      observer(newVal, oldVal) {
        if(newVal && this.data.isLoad) this.getDataPage()
      },
    },
    //过滤模块id
    filterTable: {
      type: String,
      value: ''
    },
    // 显示的表头字段 逗号分隔字符串
    showFields: {
      type: String,
      value: '',
      observer(newVal, oldVal) {},
    },
    // 查询基础条件
    baseCond: {
      type: String,
      value: '',
      observer(newVal, oldVal) {
        //230105 yan 修改传入基础条件为空时清空条件
        // if(newVal) {
        let { table, filterTable,isLoad} = this.data;
        if (!newVal){
          this.SearchWhere = null;
          if (isLoad){
            this.getDataPage()
          }
          return
        }
          //231205 yan 修改引用字段过滤条件出错问题
          let obj = JSON.parse(newVal),
              filters = [],
              filterObj = {filters: [],type: obj.type};
        // obj && (filters = eachFilter([obj]));
        obj && (filterObj = formatFilter(obj));
        /*obj.filters.forEach(item => {
            let { fieldName, filterType, operator, type, value, } = item;
            //221123 yan 修改 字段中包含tableid 则不添加tableid
            let comparewith = fieldName;
            comparewith = comparewith.indexOf('.')>=0 ? comparewith : `${filterTable || table}.${fieldName}`;
            filters.push({
              CompareValue: value,
              CompareWith: comparewith,
              Operator: operator,
              or: type === 'AND' ? 0 : 1,
            })
          });*/
          // obj.filters = filters;

        function eachFilter(arr){
          let ARR = [];
          arr.forEach(item => {
            let filters = item.filters,
              type = item.type;
            console.log(type);
            filters.forEach(ite => {
              let { fieldName, filterType, operator, value, } = ite;
              let compareWith = (ite.fieldName || ite.CompareWith);
              compareWith = compareWith.indexOf('.') >= 0 ? compareWith : (filterTable || table + '.' + compareWith);
              let obj = {
                "CompareWith": compareWith,
                "Operator": (ite.operator || ite.Operator),
                "CompareValue": (ite.value || ite.CompareValue || '').toString(),
                "or": (type?.toLowerCase() === "and" ? 0 : 1)
              };
              console.log(type?.toLowerCase());
              console.log(type?.toLowerCase() === "and");
              console.log(obj);
              ARR.push(obj);
            });
            ARR = ARR.concat(eachFilter(item.children || []));
          });
          return ARR;
        }
        function formatFilter(obj){
          let newObj = {};
          if (obj.filters){
            let filters = [];
            obj.filters.forEach(function (ite,ind, ) {
              let item = {...ite};
              let compareWith = (item.fieldName || item.CompareWith);
              compareWith = compareWith.indexOf('.') >= 0 ? compareWith : (filterTable || table + '.' + compareWith);
              let value = (item.value || item.CompareValue || '').toString(),
                Operator = item.operator || item.Operator,
                or = item.type?.toLowerCase() === "and" ? 0 : 1;
              item.CompareWith = compareWith
              filters.push({
                "CompareWith": compareWith,
                Operator,
                "CompareValue": value,
                or
              })
            });
            newObj.filters  = filters
          }
          if (obj.children){
            let children = [];
            obj.children.forEach(item => {
              let child = formatFilter(item);
              children.push(child);
            });
            newObj.children  = children;
          }
          if (obj.type){
            newObj.type = obj.type
          }
          return newObj;
        }

        // this.SearchWhere = {filters: filters,type: obj.type};
        this.SearchWhere = filterObj;
          //231205 end
          if (isLoad){
            this.getDataPage()
          }
        // }
      },
    },
    // 列表选项数据
    list: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        if(newVal) {
          let { page, pagination, optList, } = this.data
          this.setData({
            optList: newVal,
          })
          if(page === 1 || pagination) {
            this.setData({
              optList: newVal,
            })
          } else {
            optList = [ ...optList, ...newVal, ]
            this.setData({
              optList: optList,
            })
          }
        }
      },
    },
    listTotal: {
      type: Number,
      value: 0,
      observer(newVal, oldVal) {
        this.setData({
          total: newVal,
        })
      },
    },
    pageLimit: {
      type: Number,
      value: 10,
      observer(newVal, oldVal) {
        this.setData({
          limit: newVal || 10,
        })
      },
    },
    cols: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        if(newVal.length) {
          let main = [],
              sub = [],
              meven = 0,
              seven = 0
          newVal.forEach(col => {
            let type = col.type,
                isTextarea = type === 'textarea'
            if(isTextarea) col.width = true
            if(col.colType === 'sub') {
              if(isTextarea) {
                seven += (seven % 2 ? 1 : 2)
              } else {
                seven++
              }
              col.right = !(seven % 2) && !isTextarea
              sub.push(col)
            } else {
              if(isTextarea) {
                meven += (meven % 2 ? 1 : 2)
              } else {
                meven++
              }
              col.right = !(meven % 2) && !isTextarea
              main.push(col)
            }
          })
          this.setColWidth(main)
          this.setColWidth(sub)
          this.setData({
            mainCols: main,
            subCols: sub,
          })
        }
      },
    },
    // 是否需要搜索栏
    search: {
      type: Boolean,
      value: true,
    },
    // 是否需要新增
    add: {
      type: Boolean,
      value: true,
    },
    // 是否开启分页
    pagination: {
      type: Boolean,
      value: true,
    },
  },

  // 监听
  observers: {
    'table, showFields'(table, fields) {
      // if(table && fields) this.getTableCols(table, fields)
      if(table && this.data.isLoad) this.getTableCols(table, fields)
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    searchVal: '',

    scrollTop: 0,

    mainCols: [],
    subCols: [],

    optList: [],
    entityKey: '',
    page: 1,
    limit: 10,
    total: 0,

    toAdd: false,

    isLoad: false //是否加载
  },

  // 生命周期
  lifetimes: {
    created() {},
    attached() {},
    ready() {},
    moved() {},
    detached() {},
    error() {},
  },

  // 组件所在页面的生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      let { table, toAdd} = this.data;
      if(toAdd && table) { // 该组件点击过新增，重新获取第一页数据
        this.data.toAdd = false
        this.data.page = 1
        this.getDataPage()
      }
    },
    // 页面被隐藏
    hide() {},
    // 页面尺寸变化
    resize() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 双向绑定 报警告处理
    inputIpt(e) {},

    // 点击了键盘的搜索
    searchIpt(e) {
      let { table,filterTable, showFields, baseCond, searchVal, mainCols, subCols, } = this.data
      // searchVal = e.detail.value
      if(!table) {
        this.triggerEvent('search', searchVal)
        this.setData({
          scrollTop: 0,
          page: 1,
        })
        return
      }

      let filters = [];
      if(searchVal) {
        let cols = [ ...mainCols, ...subCols, ]
        if(!showFields) cols = [ cols[0], ]
        cols.forEach(field => {
          let { field_id, } = field
          filters.push({
            CompareValue: searchVal,
            CompareWith: `${filterTable || table}.${field_id}`,
            Operator: 'like',
            or: 1,
          })
        })
        // this.SearchWhere = {
        //   filters,
        //   type: 'and',
        // }
        let obj = {
          filters,
          type: 'or',
        }

        /*if(baseCond) this.SearchWhere.children = [obj]
        else this.SearchWhere = obj*/
      } /* else if(this.SearchWhere) {
        if (baseCond) delete this.SearchWhere.children
        else this.SearchWhere = null
      }*/

      this.data.page = 1
      this.getDataPage(filters)
    },
    // 清空输入框
    emptyIpt(e) {
      this.setData({
        searchVal: '',
      })
      // if(this.SearchWhere) this.SearchWhere = null

      if(!this.data.table) {
        this.triggerEvent('search', '')
        this.setData({
          scrollTop: 0,
          page: 1,
        })
        return
      }
      /*if(this.SearchWhere) {
        if(this.data.baseCond) delete this.SearchWhere.children
        else this.SearchWhere = null
      }*/
      this.data.page = 1
      this.getDataPage()
    },

    // 新增
    addData(e) {
      let { table, } = this.data
      if(table) {
        wx.navigateTo({
          url: '/DIYPages/general_edit/general_edit?entity=' + table,
        })
        this.data.toAdd = true
      } else {
        this.triggerEvent('add')
      }
    },

    // 选中选项
    select(e) {
      let { table, entityKey, } = this.data,
          selItem = e.currentTarget.dataset.item

      this.triggerEvent('select', {
        val: selItem,
        name: entityKey,
      })

      this.closePopup()
    },

    // 上一页
    prev(e) {
      let { page, pagination, table, searchVal, } = this.data
      if(!pagination || page === 1) return
      this.data.page = page - 1
      if(!table) {
        this.triggerEvent('prev', searchVal)
        this.setData({
          scrollTop: 0,
          page: this.data.page,
        })
        return
      }
      this.getDataPage()
    },
    // 下一页
    next(e) {
      let { page, pagination, limit, total, table, searchVal, } = this.data,
          max = Math.ceil(total / limit)
      if(!pagination || page === max) return
      this.data.page = page + 1
      if(!table) {
        this.triggerEvent('next', searchVal)
        this.setData({
          scrollTop: 0,
          page: this.data.page,
        })
        return
      }
      this.getDataPage()
    },
    // 滚动到底部，获取下一页
    reachBottom() {
      let { page, pagination, limit, total, table, } = this.data,
          max = Math.ceil(total / limit)
      if(pagination || page === max) return
      this.data.page = page + 1
      if(!table) {
        this.triggerEvent('next', searchVal)
        this.setData({
          page: this.data.page,
        })
        return
      }
      this.getDataPage()
    },

    closePopup(e) {
      this.setData({
        show: false,
      })
      if(e) this.triggerEvent('close')
    },
    // 重新设置col宽度
    setColWidth(rows) {
      rows.forEach((item, i) => {
        if(item.width && rows[i - 1] && !rows[i - 1].right) {
          rows[i - 1].width = true
        }
      })
      if(rows.length) {
        let last = rows[rows.length - 1]
        if(!last.width && !last.right) last.width = true
      }
    },

    // 接口
    // 1.获取表头 1.1获取模块主要显示字段 1.2根据传入的showFields查询显示字段的信息
    async getTableCols(table, fields) {
      let entityKey = await this.getMainFields(table),
          fieldsArr = fields.split(',')
      if(fields && !fieldsArr.includes(entityKey)) fieldsArr.unshift(entityKey)
      this.getFieldInfo(table, fieldsArr.join(',')).then(res => {
        let rows = res,
            even = 0
        if(!fields) {
          let idx = null,
              firstItem = null
          rows.forEach((row, r) => {
            if(row.field_id === entityKey) {
              idx = r
              firstItem = JSON.parse(JSON.stringify(row))
              return false
            }
          })
          // if(idx !== null) firstItem = rows.splice(idx, 1)[0]
          if(firstItem && idx !== null) rows.unshift(firstItem)
        }
        rows.forEach(item => {
          let { type, } = item
          if(type === 'textarea') {
            item.width = true
            even += (even % 2 ? 1 : 2)
          } else {
            even++
          }
          item.right = !(even % 2) && type !== 'textarea'
        })
        this.setColWidth(rows)
        this.setData({
          mainCols: rows,
          entityKey,
        })
      })
    },
    getMainFields(table) {
      return new Promise((resolve, reject) => {
        wx.$post(3, 'Entity_param/query_entity_param', { table_id: table, }).then(res => {
          if(res.errcode !== 0) return;
          //240626 yan 增加排序字段
          let data = res?.data?.row[0];
          let entitySortField = '';
          if (data?.sort_fields) {
            let obyArr = [], obyStr = '';
            let sort = data?.sort_fields || '',
              arr = sort.split(',');
            arr.forEach( function (item,i) {
              obyArr.push(table + "." + item);
            });
            // obyStr = obyArr.join(',') + ' asc';  //20220308 yan 取消默认升序
            obyStr = obyArr.join(',');
            entitySortField = obyStr;
          } else {
            entitySortField = '';
          }
          this.setData({
            entitySortField
          })
          // 240626 end
          resolve(res.data.row[0].entity_key)
        })
      })
    },
    getFieldInfo(table, fields) {
      return new Promise((resolve, reject) => {
        wx.$post(4, 'QX/PRO_select_field', { table, fieldname: fields, }).then(res => {
          if(res.errcode !== 0) return
          let rows = res.data.row
          resolve(rows)
        })
      })
    },
    // 2.获取选项数据
    getDataPage(where) {
      let { table,filterTable, page, limit, pagination, optList, entitySortField} = this.data,
          post = {
            table_id: filterTable || table,
            oby: entitySortField ? entitySortField : `${filterTable || table}.row_id desc`,
            page: page,
            limit: limit,
          }

      if(this.SearchWhere) post.SearchWhere = {...this.SearchWhere};
      if (where && where.length){
        if (!post.SearchWhere || !post.SearchWhere.filters || !post.SearchWhere.filters.length){
          post.SearchWhere = {filters: where,type: 'or'}
        }
        else if (!post.SearchWhere.children || !post.SearchWhere.children.length) {
          post.SearchWhere.children = [
            {filters: where,type: 'or'}
          ]
        }else {
          post.SearchWhere.children = [...post.SearchWhere.children,
            {filters: where,type: 'or'}
          ]
        }
      }

      //221123 yan 修改 自定义接口多次获取数据接口后返回204错误时，更新数据为空
      wx.$post(3, 'DynamicQuery/query_dynamic_v3', post,false,true).then(res => {
        // if(res.errcode !== 0) return
        let rows = res && res.root.data.row || [],
            obj = {
              page,
              total: res && res.root.data.total || 0,
            }
        // 开启分页
        if(pagination) {
          obj.scrollTop = 0
          obj.optList = rows
        } else {
          if(page === 1) obj.optList = rows
          else obj.optList = [ ...optList, ...rows, ]
        }

        this.setData(obj)
      })
    },
  }
})
